from web.models import CloudShop_User, CloudShop_User_Code
from web import Success_Error_Dict
from django.http import JsonResponse
from django.forms.models import model_to_dict
from decimal import Decimal
from django import forms
from web.YyTools import TypeChange
# 使用邮箱发送验证码
from django.core.mail import send_mail
import random


class CloudShop_UserForm(forms.ModelForm):
    class Meta:
        model = CloudShop_User
        fields = ['user_name', 'user_password', 'user_email']

    # 如果修改的数据有Node就保留原来的数据
    def __init__(self, *args, **kwargs):
        super(CloudShop_UserForm, self).__init__(*args, **kwargs)
        # Preserve original values
        if self.instance and self.instance.pk:
            self.initial['user_name'] = self.instance.user_name
            self.initial['user_password'] = self.instance.user_password
            self.initial['user_email'] = self.instance.user_email

    def clean(self):
        cleaned_data = super().clean()
        for field in self.Meta.fields:
            if cleaned_data.get(field) is None:
                cleaned_data[field] = getattr(self.instance, field)
        return cleaned_data


# 登录
def login(request):
    if request.method == 'POST':
        user_email = request.POST.get('user_email')
        user_password = request.POST.get('user_password')
        user_code = request.POST.get('user_code')
        if CloudShop_User_Code.objects.filter(user_email = user_email).first():
            # 判断验证码
            response = Success_Error_Dict.Error_Dict
            if CloudShop_User_Code.objects.filter(user_email = user_email).first().user_code != user_code:
                response['msg'] = '验证码错误'
                return JsonResponse(response, safe = False, status = 400)
            else:
                # 删除验证码
                CloudShop_User_Code.objects.filter(user_email = user_email).delete()
        else:
            response = Success_Error_Dict.Error_Dict
            response['msg'] = '请先获取验证码'
            return JsonResponse(response, safe = False, status = 400)

        # 判断数据库中是否存在该邮箱
        try:
            user_data = CloudShop_User.objects.filter(user_email = user_email).first()
            if user_data:
                # 存在用户, 判断密码是否正确
                if user_data.user_password == user_password:
                    # 密码正确, 登录成功
                    response = Success_Error_Dict.Success_Dict
                    response['msg'] = '登录成功'
                    response['data'] = model_to_dict(user_data)
                    return JsonResponse(response, safe = False, status = 200)
                else:
                    # 密码错误, 登录失败
                    response = Success_Error_Dict.Error_Dict
                    response['msg'] = '密码错误, 登录失败'
                    return JsonResponse(response, safe = False, status = 400)
            else:

                # 不存在用户, 注册用户
                user_data = CloudShop_User.objects.create(
                    user_name = 'YyCloudUser',
                    user_password = user_password,
                    user_email = user_email
                )
                response = Success_Error_Dict.Success_Dict
                response['msg'] = '注册成功'
                response['data'] = model_to_dict(user_data)

                return JsonResponse(response, safe = False, status = 200)
        except Exception as e:
            return JsonResponse(Success_Error_Dict.Server_Error_Dict, safe = False, status = 400)
    else:
        return JsonResponse(Success_Error_Dict.Request_Error_Dict, safe = False, status = 400)


# 发送验证码
def send_code(request):
    def code_temp1(user_emails):
        scode = random.randint(1000, 9999)
        send_mail(
            subject = '云商城验证码',
            message = '您的验证码是: ' + str(scode),
            from_email = '18171759943@163.com',
            recipient_list = user_emails,
            fail_silently = False
        )
        return scode

    if request.method == 'POST':
        user_email = request.POST.get('user_email')
        # 判断数据库中是否存在该邮箱
        try:
            user_data = CloudShop_User_Code.objects.filter(user_email = user_email).first()
            if user_data:
                # 存在邮箱, 更新验证码
                code = code_temp1([user_email])
                CloudShop_User_Code.objects.filter(
                    user_email = user_email,
                ).update(user_code = code)
                response = Success_Error_Dict.Success_Dict
                response['msg'] = '验证码发送成功'
                response['data'] = None
                return JsonResponse(response, safe = False, status = 200)
            else:
                # 不存在邮箱, 创建验证码
                code = code_temp1([user_email])
                CloudShop_User_Code.objects.create(
                    user_email = user_email,
                    user_code = code
                )
                response = Success_Error_Dict.Success_Dict
                response['msg'] = '验证码发送成功'
                response['data'] = None
                return JsonResponse(response, safe = False, status = 200)
        except Exception as e:
            print(e)
            return JsonResponse(Success_Error_Dict.Server_Error_Dict, safe = False, status = 400)
    else:
        return JsonResponse(Success_Error_Dict.Request_Error_Dict, safe = False, status = 400)


# 修改我的信息
def edit_info(request):
    if request.method == 'POST':
        response = Success_Error_Dict.Error_Dict
        user_id = request.POST.get('id')
        if user_id is None:
            response['msg'] = '请提供用户id'
            return JsonResponse(response, status = 400, safe = False, content_type = 'application/json')
        user_info = CloudShop_User.objects.filter(id=user_id).first()
        form = CloudShop_UserForm(request.POST, instance=user_info)
        if form.is_valid():
            form.save()
            response['code'] = 200
            response['msg'] = '修改成功'
            form.cleaned_data['money'] = user_info.money
            form.cleaned_data['id'] = user_info.id
            response['data'] = form.cleaned_data
            return JsonResponse(response, status = 200)
        # 获取第一个错误消息
        first_error_field = list(form.errors.keys())[0]
        first_error_message = form.errors[first_error_field][0]
        response['msg'] = f'修改失败: {first_error_message}'
        return JsonResponse(response, status = 400)
    else:
        return JsonResponse(Success_Error_Dict.Error_Dict, status = 400)


# 支付通道
# 云支付
def pay_cloud(request):
    if request.method == 'POST':
        response = Success_Error_Dict.Error_Dict
        user_id = request.POST.get('id')
        try:
            recharge_amount = float(request.POST.get('recharge_amount', '1.00'))
            print(recharge_amount)
            # 判断金额是否小于0
            if recharge_amount < 0.99:
                response['msg'] = '充值金额太少了'
                return JsonResponse(response, status = 400, safe = False, content_type = 'application/json')
        except ValueError as e:
            response['msg'] = '充值金额格式错误'
            return JsonResponse(response, status = 400, safe = False, content_type = 'application/json')

        if user_id is None:
            response = Success_Error_Dict.Error_Dict
            response['msg'] = '请提供用户id'
            return JsonResponse(response, status = 400, safe = False, content_type = 'application/json')
        else:
            user_info = CloudShop_User.objects.filter(id = user_id).first()
            if user_info is None:
                response['msg'] = '用户不存在'
                return JsonResponse(response, status = 400, safe = False, content_type = 'application/json')
            else:
                user_money = float(user_info.money)
                total = TypeChange.type_change_Decimal(user_money + recharge_amount)
                CloudShop_User.objects.filter(id = user_id).update(
                    money = total
                )
                response['code'] = 200
                response['msg'] = '充值成功'
                response['data'] = model_to_dict(CloudShop_User.objects.filter(id = user_id).first())

                # 删除敏感数据
                del response['data']['user_password']
                return JsonResponse(response, status = 200, safe = False, content_type = 'application/json')

    else:
        return JsonResponse(Success_Error_Dict.Request_Error_Dict, safe = False, status = 400)
